// pages/compiler/compiler.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    screenHeight: app.globalData.screenHeight,
    diary: {
      title: '舔狗日记',
      content: '她好像从来没有说过爱我，我搜索了一下关键字爱。在我们的聊天记录里，她只说过一',
      url: '',
      qrCode: ''
    },
    isLoadCanvas: false,
    isTitle: false,
    isTitleFocus: false,
    isContent: false,
    isContentFocus: false,
    canvasWidth: 600,
    canvasHeight: 600,
    canvasPicWidth: 130,
    canvasPicHeight: 110
  },
  getImageInfo: function (field, path) {
    let that = this
    let fliePath = path || that.data.diary.url
    wx.getImageInfo({
      src: fliePath,
      success: function (res) {
        let url = 'diary.' + field + ''
        that.setData({
          [url]: res.path
        })
      },
      fail: function (res) {
        console.log(res)
      },
    })
  },
  /**
   * canvas
   * @param {canvas} options 
   */
  canvasLoad: function () {
    let that = this
    const ctx = wx.createCanvasContext('netease')

    ctx.setFillStyle("#FFF")
    ctx.fillRect(0, 0, 300, 600)
    ctx.setFillStyle("#000")
    ctx.font = 'normal bold 17px sans-serif';
    ctx.textAlign = "center";
    ctx.fillText(that.data.diary.title, 300 / 2, 20 + that.data.canvasPicHeight + 17)
    ctx.textAlign = "left";
    ctx.font = 'normal bold 17px sans-serif';
    // 自动换行
    let initHeight = that.drawText(ctx, that.data.diary.content, 10, 45 + that.data.canvasPicHeight + 17, 20 + that.data.canvasPicHeight + 80, 250)
    ctx.drawImage(that.data.diary.qrCode, 0, 0, 70, 70)
    ctx.drawImage(that.data.diary.url, (300 - that.data.canvasPicWidth) / 2, 20, that.data.canvasPicWidth, that.data.canvasPicHeight)
    ctx.setGlobalAlpha(0);
    ctx.draw(true, () => {
      that.saveImage(initHeight);
    })
  },
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 17; //17
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    console.log('initHeight::', initHeight);
    console.log('titleHeight::', titleHeight);
    // 标题border-bottom 线距顶部距离
    initHeight = initHeight + 10;
    titleHeight = titleHeight + 10;
    return initHeight;
  },
  saveImage: function (initHeight) {
    let that = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 300,
      height: initHeight,
      destWidth: 300,
      destHeight: initHeight,
      canvasId: 'netease',
      fileType: 'jpg',
      quality: 1,
      success(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            that.setData({
              isLoadCanvas: !that.data.isLoadCanvas
            })
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 1500
            })
            wx.hideLoading();
          }
        })
      }
    })
  },
  picReplace: function () {
    let that = this
    wx.chooseImage({
      count: 1,
      success: async (res) => {
        that.doImgSecCheck(res.tempFilePaths[0], 'png')
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },

  /**
   * 珊瑚图片内容安全
   */
  doImgSecCheck: function (path) {
    let that = this
    wx.showLoading({
      title: '正在更换',
      mask: true
    })
    wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: 'servicemaket/'+(new Date().getTime())+'.png',
      // 指定要上传的文件的小程序临时文件路径
      filePath: path,
      // 成功回调
      success: res => {
        wx.cloud.getTempFileURL({
          fileList: [res.fileID],
          success: res => {
            let file = res.fileList[0].tempFileURL
            wx.serviceMarket.invokeService({
              service: 'wxee446d7507c68b11',
              api: 'imgSecCheck',
              data: {
                "Action": "ImageModeration",
                "Scenes": ["PORN", "POLITICS", "TERRORISM"],
                "ImageUrl": file,
                "Config": "",
                "Extra": ""
              },
            }).then(res_info => {              
              let check = res_info.data.Response.Suggestion
              wx.hideLoading()
              if (check !== 'PASS') {
                wx.showModal({
                  title: '警告',
                  content: '图片内容违规',
                })
              } else {
                let url = 'diary.url'
                that.setData({
                  [url]: path
                })
              }
            })
          },
          fail: console.error
        })
      },
    })
  },
   /**
   * 珊瑚文字内容安全
   */
  doMsgSecCheck: function (titleValue, titleField, isFieId, isFocusFieId) {
    let that = this
    wx.serviceMarket.invokeService({
      service: 'wxee446d7507c68b11',
      api: 'msgSecCheck',
      data: {
        "Action": "TextApproval",
        "Text": titleValue
      },
    }).then(res => {
      console.log(res);
      
      let EvilTokens = res.data.Response.EvilTokens
      if (EvilTokens.length !== 0) {
        wx.showModal({
          title: '警告',
          content: '输入有违规词',
        })
        that.setData({
          [titleField]: '',
        })
      }else {
        that.setData({
          [titleField]: titleValue,
          [isFieId]: !that.data[isFieId],
          [isFocusFieId]: !that.data[isFocusFieId]
        })
      }
    })
  },

  titleEdit: function () {
    let that = this
    that.setData({
      isTitle: !that.data.isTitle,
      isTitleFocus: !that.data.isTitleFocus
    })
  },
  titleInputBlur: function (event) {
    let that = this
    let titleField = 'diary.title'
    let titleValue = event.detail.value
    that.doMsgSecCheck(titleValue, titleField, 'isTitle', 'isTitleFocus')
  },
  contentEdit: function () {
    let that = this
    that.setData({
      isContent: !that.data.isContent,
      isContentFocus: !that.data.isContentFocus,
    })
  },
  contentInputBlur: function (event) {
    let that = this
    let titleField = 'diary.content'
    let titleValue = event.detail.value
    that.doMsgSecCheck(titleValue, titleField, 'isContent', 'isContentFocus')
  },
  save: function () {
    let that = this
    wx.showLoading({
      title: '正在保存',
    });
    that.setData({
      isLoadCanvas: !that.data.isLoadCanvas
    })
    setTimeout(() => {
      that.settingUser()
    }, 500)
  },
  settingUser: function () {
    let that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              setTimeout(() => {
                that.canvasLoad()
              }, 500)
            },
            fail() {
              wx.hideLoading()
              that.showModal()
            }
          })
        } else {
          setTimeout(() => {
            that.canvasLoad()
          }, 500)
        }
      }
    })
  },
  showModal: function () {
    wx.showModal({
      title: '提示',
      content: '请授权保存图片功能',
      cancelText: '关闭',
      cancelColor: '#999',
      confirmText: '去授权',
      confirmColor: '#f94218',
      success(res) {
        if (res.confirm) {
          wx.openSetting({
            success(res) {
              console.log(res.authSetting)
            }
          })
        } else {
          wx.hideLoading();
        }
      }
    })
  },
  randomContent: function () {
    wx.showLoading({
      title: '加载中',
    })
    this.queryContent();
  },
  queryContent: function () {
    let that = this
    let contentFieId = 'diary.content'
    wx.cloud.callFunction({
      name: 'test',
      success: res => {
        let data = res.result.list
        that.setData({
          [contentFieId]: data[0].content
        })
        wx.hideLoading()
      },
      fail: console.error
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getImageInfo('url', 'https://736d-smalltool-5ezhy-1301553765.tcb.qcloud.la/default.jpg')
    this.getImageInfo('qrCode', 'https://736d-smalltool-5ezhy-1301553765.tcb.qcloud.la/qr_code.jpg')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})